let fs = require('fs');
let path = require('path');
let moment = require('moment');
let util = require('util');
let os = require('os');
let logDir = path.join(__dirname + '../../../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}
let info = fs.createWriteStream(logDir + '/info.log', {flags: 'a', mode: '0666'});
let error = fs.createWriteStream(logDir + '/error.log', {flags: 'a', mode: '0666'});
let _logger = new console.Console(info, error);
const format = function (msg) {
  let ret = '';
  if (!msg) {
    return ret;
  }

  let date = moment();
  let time = date.format('YYYY-MM-DD HH:mm:ss.SSS');
  if (msg instanceof Error) {
    let err = {
      name: msg.name,
      data: msg.data
    };

    err.stack = msg.stack;
    ret = util.format('%s %s: %s\nHost: %s\nData: %j\n\n',
        time,
        err.name,
        err.stack,
        os.hostname(),
        date
    );
  } else {
    ret = time + ' ' + util.format.apply(util, arguments) + '\n';
  }
  return ret;
};

function write(path, information, type) {
  try {
    fs.writeFileSync(path, information, {flag: type || "a"});
  } catch (e) {
    throw new Error(e);
  }
}

let t = {
  error(msg) {
    _logger.error(format(msg))
  },
  log(msg) {
    _logger.log(format(msg))
  },
  format(msg) {
    return format(msg);
  },
  clear() {
    write(logDir + '/error.log', '', 'w+');
    write(logDir + '/info.log', '', 'w+');
  }
};

module.exports = t;
